var map = new BMap.Map("container");          // 创建地图实例
var myGeo = new BMap.Geocoder();//地址逆解析
var items = document.getElementsByTagName("p");
var time;
var hour;
var minute;
var second;
var pictures = new Array('first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth');
var point = new BMap.Point(123.433046, 41.794778);
map.centerAndZoom(point, 14);             // 初始化地图，设置中心点坐标和地图级别
map.setCurrentCity("沈阳");		//设置当前显示城市
map.enableScrollWheelZoom(); // 允许滚轮缩放
heatmapOverlay = new BMapLib.HeatmapOverlay({"radius": 100, "visible": true});
heatmapOverlay.imei = "heat";
map.addOverlay(heatmapOverlay);
//heatmapOverlay.disableMassClear();
//动态加载热力图

function getAddress(lat, lon, i) {//得到附近的商圈信息
    var add = "正在查询商圈信息";
    myGeo.getLocation(new BMap.Point(lat, lon), function (result) {
        if (result) {
            add = "商圈信息:\n"+result.business;
            if (result.business.length == 0) {
                add = "暂无商圈信息";
            }
            items[i].innerText = add;
        }
    })
    console.log(add);
}

// 用于热力图坐标转换的全局变量
let tempArray = [];
let originData = [];
let finalData = [];
function f(args) {
    // 刷新热力图
    $.ajax({
        type: "POST",
        url: "/count/print",
        // dataType: 'json',
        async: false,
        success: function (res) {
            if (res.length) {
                originData = res;

                // 将originData分组放进tempArray中，每组100条数据
                let temp = [];
                for (let i = 0; i < originData.length; i++) {
                    temp.push([originData[i].longitude, originData[i].latitude]);
                    if (i % 100 == 99 || i == originData.length - 1) {
                        tempArray.push(temp);
                        temp = [];
                    }
                }

                genFinalData(0, tempArray.length);
            }
        },
        error: function () {
            alert("获取数据失败，请检查数据库是否正常");
            // cities = [
            //     {"lng": "123.415969", "lat": "41.807781", "count": "1"},
            //     {"lng": "123.411911", "lat": "41.810459", "count": "50"},
            //     {"lng": "123.426200", "lat": "41.813289", "count": "100"},
            //     {"lng": "114.395983", "lat": "36.201385", "count": "19"},
            // ];
        }
    });

    // 刷新top10
    var tops = [];
    $.ajax({
        type: "POST",
        url: "/count/top",
        dataType: 'json',
        async: false,
        success: function (countLi) {
            // 用于坐标转换的局部变量
            let temp = [];
            let originData = countLi;
            let finalData = [];

            for (var i = 0; i < originData.length; i++) {
                temp.push([originData[i].longitude, originData[i].latitude]);
            }

            temp = temp.join(";");
            $.ajax({
                type: "GET",
                url: "http://api.map.baidu.com/geoconv/v1/?coords=" + temp + "&from=3&to=5&ak=SipXZFGUXfBvDr88wUQHGdwhP06tY5Bz",
                dataType: "jsonp",
                cache: false,
                success: function (res) {
                    for (let j = 0; j < res.result.length; j++) {
                        finalData.push({
                            "lng": res.result[j].x,
                            "lat": res.result[j].y,
                            "count": originData[j].count
                        });

                        getAddress(finalData[j].lng, finalData[j].lat, j + 1);
                    }

                    tops = finalData;

                    time = countLi[0].time;
                    hour = time.slice(8, 10);
                    minute = time.slice(10, 12);
                    second = time.slice(12, 14);
                    var show = hour + ":" + minute + ":" + second + "| 每1.5秒自动刷新";
                    $('#date').empty();
                    $('#date').append(show);

                    refresh();
                    for (var i = tops.length - 1; i >= 0; i--) {
                        addMarker(tops[i].lng, tops[i].lat, pictures[i], i);
                    }
                }
            });
        },
        error: function () {
            tops = [];
        }
    });
}

function genFinalData(index, length) {
    let temp = tempArray[index].join(';');
    // 利用百度接口转换坐标
    $.ajax({
        type: "GET",
        url: "http://api.map.baidu.com/geoconv/v1/?coords=" + temp + "&from=3&to=5&ak=SipXZFGUXfBvDr88wUQHGdwhP06tY5Bz",
        dataType: "jsonp",
        cache: false,
        success: function (res) {
            for (let j = 0; j < res.result.length; j++) {
                finalData.push({
                    "lng": res.result[j].x,
                    "lat": res.result[j].y,
                    "count": originData[index * 100 + j].count
                });
            }
            if (++index != length) {
                // 为解决ajax异步问题使用递归
                genFinalData(index, length);
            } else {
                // 所有坐标都转换完成后生成热力图
                heatmapOverlay.setDataSet({data: finalData, max: 100});
                heatmapOverlay.show();

                // 清空
                finalData = [];
                tempArray = [];
                // 结束递归
                return;
            }
        }
    });
}

f();

//定时刷新热力图
setInterval(f, 1500);

function addMarker(longt, lati, string, i) {
    var pt = new BMap.Point(longt, lati);
    // 创建自定义图标对象
    var myIcon = new BMap.Icon('/img/' + string + '.png', new BMap.Size(117, 145));
    var marker = new BMap.Marker(pt, {icon: myIcon});  // 创建标注
    marker.imei = "able";
    map.addOverlay(marker);
    switch (i) {//不同的I值绑定不同的事件
        case 0:
            marker.addEventListener("click", function () {
                $('#collapseOne').collapse('toggle');
            });
            break;
        case 1:
            marker.addEventListener("click", function () {
                $('#collapseTwo').collapse('toggle');
            });
            break;
        case 2:
            marker.addEventListener("click", function () {
                $('#collapseThree').collapse('toggle');
            });
            break;
        case 3:
            marker.addEventListener("click", function () {
                $('#collapseFour').collapse('toggle');
            });
            break;
        case 4:
            marker.addEventListener("click", function () {
                $('#collapseFive').collapse('toggle');
            });
            break;
        case 5:
            marker.addEventListener("click", function () {
                $('#collapseSix').collapse('toggle');
            });
            break;
        case 6:
            marker.addEventListener("click", function () {
                $('#collapseSeven').collapse('toggle');
            });
            break;
        case 7:
            marker.addEventListener("click", function () {
                $('#collapseEight').collapse('toggle');
            });
            break;
        case 8:
            marker.addEventListener("click", function () {
                $('#collapseNine').collapse('toggle');
            });
            break;
        case 9:
            marker.addEventListener("click", function () {
                $('#collapseTen').collapse('toggle');
            });
            break;
    }

}

if (!isSupportCanvas()) {
    alert('热力图目前只支持有canvas支持的浏览器,您所使用的浏览器不能使用热力图功能~')
}

//每次刷新之前删除之前的覆盖物
function refresh() {
    var len = map.getOverlays().length;
    for (var i = len; i > 0; i--) {
        if (map.getOverlays()[i - 1].imei == "able")
            map.removeOverlay(map.getOverlays()[i - 1]);
    }
}

//判断浏览区是否支持canvas
function isSupportCanvas() {
    var elem = document.createElement('canvas');
    return !!(elem.getContext && elem.getContext('2d'));
}

function setGradient() {
    /*格式如下所示:
    {
        0:'rgb(102, 255, 0)',
        .5:'rgb(255, 170, 0)',
        1:'rgb(255, 0, 0)'
    }*/
    var gradient = {};
    var colors = document.querySelectorAll("input[type='color']");
    colors = [].slice.call(colors, 0);
    colors.forEach(function (ele) {
        gradient[ele.getAttribute("data-key")] = ele.value;
    });
    heatmapOverlay.setOptions({"gradient": gradient});
}
